import { OnDestroy, Component } from '@angular/core';
import { UntypedFormBuilder, Validators, UntypedFormGroup, UntypedFormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'passport-reset',
  templateUrl: './reset.component.html',
  styleUrls: ['./reset.component.less']
})
export class ResetPasswordComponent implements OnDestroy {
  email: string = '';
  constructor(
    fb: UntypedFormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    public http: _HttpClient,
    public msg: NzMessageService
  ) {
    this.form = fb.group({
      password: [
        null,
        [Validators.required, Validators.minLength(6), Validators.maxLength(16), ResetPasswordComponent.checkPassword.bind(this)]
      ],
      confirm: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16), this.passwordEquar]],
      captcha: [null, [Validators.required, Validators.minLength(6)]],
      username: [null, [Validators.required]],
      email: [null, [Validators.required]]
    });
    this.route.queryParams.subscribe((res: any) => {
      if (!res) {
        this.msg.error('参数有误');
        return;
      }
      this.email = res.email;
    });
  }
  get password() {
    return this.form.controls['password'];
  }
  get confirm() {
    return this.form.controls['confirm'];
  }
  form: UntypedFormGroup;
  error = '';
  type = 0;
  visible = false;
  status: string = 'pool';
  progress = 0;
  passwordProgressMap: { [key: string]: 'success' | 'normal' | 'exception' } = {
    ok: 'success',
    pass: 'normal',
    pool: 'exception'
  };
  count = 0;
  interval$: any;

  pattern_1 = /^.*([0-9])+.*$/i; //数字
  pattern_2 = /[a-z]/; //小写字母
  pattern_3 = /[A-Z]/; //大写字母
  pattern_4 = /[`~!@#$%^&*()\-_+=\\|{}':;\",\[\].<>\/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]/; //特殊字符

  static checkPassword(control: UntypedFormControl): NzSafeAny {
    if (!control) return null;
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    const self: any = this;
    self.visible = !!control.value;
    // if (control.value && control.value.length > 9) {
    //   self.status = 'ok';
    // } else if (control.value && control.value.length > 5) {
    //   self.status = 'pass';
    // } else {
    //   self.status = 'pool';
    // }
    if (!control.value) {
      self.status = 'pool';
    }
    let level = 0;
    if (control.value && control.value.length < 6) {
      self.status = 'pool';
    } else if (control.value && control.value.length > 6) {
      if (self.pattern_1.test(control.value)) {
        level++;
      }
      if (control.value.length > 10) {
        level++;
      }
      if (self.pattern_2.test(control.value) || self.pattern_3.test(control.value)) {
        level++;
      }
      if (self.pattern_4.test(control.value)) {
        level++;
      }
      if (level <= 1) {
        self.status = 'pool';
      } else if (level <= 3) {
        self.status = 'pass';
      } else {
        self.status = 'ok';
      }
    } else {
      self.status = 'pool';
    }

    if (self.visible) {
      self.progress = control.value.length * 10 > 100 ? 100 : control.value.length * 10;
    }
  }

  passwordEquar(control: UntypedFormControl) {
    if (!control || !control.parent) {
      return null;
    }
    // tslint:disable-next-line: no-non-null-assertion
    if (control.value !== control.parent.get('password')!.value) {
      return { equar: true };
    }
    return null;
  }

  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }

  submit(): void {
    this.error = '';
    Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      this.form.controls[key].updateValueAndValidity();
    });
    if (this.form.invalid) {
      console.log(this.form.errors);
      // this.msg.error(this.form.errors);
      return;
    }
    debugger;
    const data = {
      username: this.form.value['username'],
      newPwd: this.form.value['password'],
      email: this.form.value['email'],
      code: this.form.value['captcha']
    };
    this.http.post(Api.ResetPassordApi, null, data).subscribe(res => {
      if (res) {
        if (res.code === ResponseCode.SUCCESS) {
          this.router.navigate(['/passport/login'], { queryParams: { email: data.email } });
        } else {
          this.msg.error(res ? (res.data ? res.data : '重置失败，未知原因！') : '重置失败，未知原因！');
        }
      } else {
        this.msg.error('重置失败，未知原因！');
      }
    });
  }
}
